package cn.chenfeifx.checker.model;

import cn.chenfeifx.checker.CheckerApp;
import cn.chenfeifx.checker.eneity.ExportDataModel;
import cn.chenfeifx.checker.eneity.MessageEntity;
import cn.chenfeifx.checker.eneity.ReportEntity;
import cn.chenfeifx.checker.enums.CheckerEnum;
import cn.chenfeifx.checker.thread.CheckRunable;
import cn.chenfeifx.checker.thread.CheckRunable2;
import cn.chenfeifx.core.common.LoadingUtils;
import cn.chenfeifx.core.common.SimpleButton;
import cn.chenfeifx.core.controls.CFFileChooser;
import cn.chenfeifx.core.controls.CFMessage;
import cn.chenfeifx.core.controls.CFTableView;
import cn.chenfeifx.core.controls.model.Column;
import cn.chenfeifx.core.enums.Level;
import com.alibaba.excel.EasyExcel;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CheckNav2 extends StackPane {

    private CFTableView cfTableView = CheckerApp.getInstance().getCfTableView2();
    private CFFileChooser cfFileChooser = new CFFileChooser();
    Button button2 = SimpleButton.get("加载著录表", Level.SUCCESS);
    Button button3 = SimpleButton.get("开始质检", Level.SUCCESS);
    Button button4 = SimpleButton.get("导出报告", Level.SUCCESS);
    Button button5 = SimpleButton.get("开始分件", Level.SUCCESS);
    HBox hBox = new HBox(cfFileChooser,button2,button3,button4);
    HBox hBox2 = new HBox(cfTableView);
    VBox vBox = new VBox(hBox,hBox2);
    String maxreference = "";

    String minreference = "";

    public CheckNav2() {
        hBox.setMaxSize(USE_PREF_SIZE, USE_PREF_SIZE);
//        hBox.setAlignment(Pos.TOP_LEFT);
        hBox.setSpacing(10);
        getChildren().addAll(vBox);
        AtomicBoolean loading = new AtomicBoolean(false);
        setPadding(new Insets(20));
        ExecutorService executor = Executors.newFixedThreadPool(8); // 创建固定大小的线程池
        BlockingQueue<ReportEntity> queue = new LinkedBlockingQueue<>();
        Set<ReportEntity> reports = new HashSet<>();
        List<Future<?>> futureList = new ArrayList<>();



        button3.setDisable(true);
        button4.setDisable(false);
        button5.setDisable(true);
        // 创建列
        List<Column> columns = Arrays.asList(
                new Column("全宗号","completeNumber",150d),
                new Column("类目号","categoryNumber",100d),
                new Column("件号","caseNumber",100d),
                new Column("档号","reference",150d),
                new Column("责任者","author",100d),
                new Column("文号","referenceNumber",100d),
                new Column("题名","titleName",50d),
                new Column("日期","date",150d),
                new Column("页数","pageNumber",100d),
                new Column("年度","year",100d),
                new Column("保管期限","term",100d),
                new Column("密级","security",100d),
                new Column("开放状态","openState",100d),
                new Column("备注","remark",100d)
        );
        TableColumn<ReportEntity,String> photoColumn = new TableColumn<>("状态");
        photoColumn.setCellFactory(column ->new TableCell<ReportEntity, String>() {
            private final ImageView imageView = new ImageView();
            {
                imageView.setFitWidth(20);
                imageView.setFitHeight(20);
            }

            @Override
            protected void updateItem(String status, boolean empty) {
                super.updateItem(status, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    if( status!=null){
                        Image image = new Image(status);
//                        Image image = new Image("/img/loading.gif");
                        imageView.setImage(image);
                        setGraphic(imageView);
                    }
                }
            }
        });
        photoColumn.setCellValueFactory(cellData ->cellData.getValue().getStatusPath());
        cfTableView.createColumns(columns);
        cfTableView.getColumns().add(photoColumn);

        button2.setOnMouseClicked(event ->
                LoadingUtils.nodeLoad(this, () -> {
                    //模拟数据
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            // 在这个里边可以执行业务逻辑
                            try {
                                if(cfFileChooser.getFile()==null){
                                    CFMessage.show("请选择文件", Level.DANGER);
                                }
                                File file = cfFileChooser.getFile();
                                List<ReportEntity> reports = EasyExcel.read(new FileInputStream(file)).head(ReportEntity.class)
                                        .sheet()
                                        .doReadSync();
                                int index = 1;
                                if(reports!=null){
                                    for (ReportEntity report : reports){
                                        report.setIndex(index++);
                                        report.setStatusPath("/img/loading.gif");
                                    }
                                    // 设置数据
                                    cfTableView.setItems(reports);
                                    button2.setDisable(true);
                                    button3.setDisable(false);
                                    button5.setDisable(false);
                                    maxreference = reports.get(reports.size()-1).getReference();
                                    minreference = reports.get(0).getReference();
                                }


                            } catch (FileNotFoundException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
                    return true;
                }));

        button3.setOnMouseClicked(event ->
                LoadingUtils.nodeLoad(this,() -> {
//                    loading.set(true);
                    button3.setDisable(true);
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            // 在这个里边可以执行业务逻辑
                            try {
                                File file = cfFileChooser.getFile();
                                String parentPath = file.getParent();
                                List<ReportEntity> items = cfTableView.getItems();
                                // 校验案卷
                                Integer index = 1;
                                for (ReportEntity report : items){
                                    Future<?> submit = executor.submit(new CheckRunable2(
                                            index++,
                                            report,
                                            parentPath));
                                    futureList.add(submit);
                                }
                                //queue.addAll(items);

                                executor.shutdown(); // 关闭线程池

                            } catch (Exception e) {
                                CFMessage.show("质检失败", Level.DANGER);
                                throw new RuntimeException(e);

                            }
                        }
                    });
                    new Runnable(){
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }

                            int completedTasks = 0;
                            while (true) {
                                int currentCompletedTasks = 0;
                                for (Future<?> future : futureList) {
                                    if (future.isDone()) {
                                        currentCompletedTasks++;
                                    }
                                }
                                if (currentCompletedTasks > completedTasks) {
                                    completedTasks = currentCompletedTasks;
                                    System.out.println("Completed tasks: " + completedTasks + ", still waiting...");
                                }
                                if (completedTasks == futureList.size()) {
                                    System.out.println("所有线程任务已完成");
                                    button4.setDisable(false);
                                    CFMessage.show("质检完成", Level.SUCCESS);
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    Thread.currentThread().interrupt();
                                }
                            }

                        }
                    };
                    return true;
                }));

        button4.setOnMouseClicked(event ->
                LoadingUtils.nodeLoad(this,() -> {
//                    button4.setDisable(true);
                    Platform.runLater(
                            new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        if(cfFileChooser.getFile()==null){
                                            CFMessage.show("请选择文件", Level.DANGER);
                                        }
                                        String parent = cfFileChooser.getFile().getParent();
                                        List<MessageEntity> messageList = CheckerApp.getInstance().getMessageList(CheckerEnum.ONE_PIECE.getCode());

                                        messageList = new ArrayList<>(messageList.stream()
                                                .collect(Collectors.toMap(
                                                        MessageEntity::getReference,  // 根据 reference 去重
                                                        Function.identity(),          // 保留 MessageEntity 实例本身
                                                        (existing, replacement) -> existing  // 如果遇到重复的 reference，保留第一个
                                                ))
                                                .values());

                                        List<ExportDataModel> reports = CheckerApp.getInstance().getReports(CheckerEnum.ONE_PIECE.getCode());

                                        ExportFile.exportExcel(
                                                parent+"/永和县档案馆一文一件档案数据质量检测记录表.xlsx",
                                                reports,
                                                "",
                                                "",
                                                ExportFile.addFile(parent),
                                                minreference+"-"+maxreference);

//                                    EasyExcel.write( new FileOutputStream(new File(parent+"/质检报告.xlsx")), Report.class)
//                                            .autoCloseStream(Boolean.FALSE)
//                                            .sheet("质检报告")
//                                            .doWrite(reports);
                                        EasyExcel.write( new FileOutputStream(new File(parent+"/一文一件错误详情.xlsx")), MessageEntity.class)
                                                .autoCloseStream(Boolean.FALSE)
                                                .sheet("错误详情")
                                                .doWrite(sortList(messageList));
                                        CFMessage.show("报告导出成功，请在目录文件夹下查看！", Level.SUCCESS);

                                    } catch (FileNotFoundException e) {
                                        throw new RuntimeException(e);
                                    } catch (Exception e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            }
                    );
                    return true;
                }));
    }

    public static List<MessageEntity> sortList(List<MessageEntity> list){

        Comparator<MessageEntity> comparatorByAgeDesc = (map1, map2) -> {
            String value1 = map1.getReference();
            String value2 = map2.getReference();
            return - value2.compareTo(value1);
        };
        Collections.sort(list, comparatorByAgeDesc);
        return list;
    }
}
